﻿#include "coalform.h"
#include "ui_coalform.h"
#include "singleton.h"
#include "myapp.h"
CoalForm::CoalForm(QWidget* parent) :
    QWidget(parent),
    ui(new Ui::CoalForm),
    show_alarmExtern(false)
{
    ui->setupUi(this);
    m_chart = new QChart();
    ui->graphicsView_coalLine->setChart(m_chart);

    m_vAxisY = new QValueAxis();
    m_vAxisY->setRange(0, 100);
    m_vAxisY->setLabelFormat("%0.0f");
    m_vAxisY->setTickCount(11);

    m_dateAxisX = new QDateTimeAxis();
    m_dateAxisX->setFormat("hh:mm:ss");
    m_dateAxisX->setLabelsAngle(30);
    m_dateAxisX->setTickCount(7);

    m_series = new QLineSeries();
    m_chart->addSeries(m_series);
    m_chart->setTheme(QtCharts::QChart::ChartThemeBlueCerulean);
    m_chart->legend()->hide();
    m_chart->addAxis(m_vAxisY, Qt::AlignLeft);
    m_chart->addAxis(m_dateAxisX, Qt::AlignBottom);

    m_series->attachAxis(m_vAxisY);
    m_series->attachAxis(m_dateAxisX);
    this->on_btn_getparam_clicked();

    m_timer = new    QTimer(this);
    m_timer->setInterval(500);
    m_timer_2 = new    QTimer(this);
    m_timer_2->setInterval(1000);
    connect(m_timer, &QTimer::timeout, this, [ = ]
    {
        QJsonObject body;
        body.insert("chnId", myApp::current_chnnid);
        Singleton::Instance()->onSendParam("GetOriginImage", body);
    });
    connect(m_timer_2, &QTimer::timeout, this, [ = ]
    {
        QJsonObject body;
        Singleton::Instance()->onSendParam("SetCoalSpdDebug", body);
    });
    ui->tabWidget->setCurrentIndex(0);

    connect(Singleton::Instance(), &Singleton::sigSetAlarmInfoSuccess, this, [ = ]()
    {
        if(ui->btn_coalimage->text() == "关闭预览")
        {
            ui->btn_coalimage->setText("打开预览");
            ui->widget_coalSection->clear();
            QMessageBox::information(nullptr, "提示", "实时预览关闭成功");
        }
        else
        {
            ui->btn_coalimage->setText("关闭预览");
        }
    }, Qt::QueuedConnection);
    connect(Singleton::Instance(), &Singleton::sigSetColidarPileCoalParamSuccess, this, [ = ]()
    {
        QMessageBox::information(nullptr, "提示", "激光雷达堆煤参数设置成功");
    }, Qt::QueuedConnection);
    connect(Singleton::Instance(), &Singleton::sigSetCoalSpdParamSuccess, this, [ = ]()
    {
        QMessageBox::information(nullptr, "提示", "煤量调速参数设置成功");
    }, Qt::QueuedConnection);

    connect(Singleton::Instance(), &Singleton::sigSetCoalSpdBaselineSuccess, this, [ = ]()
    {
        QMessageBox::information(nullptr, "提示", "煤量基准设置成功");
    }, Qt::QueuedConnection);
}

CoalForm::~CoalForm()
{
    delete ui;
}



void CoalForm::on_btn_draw_clicked(bool checked)
{
    if(checked)
    {
        show_alarmExtern = false;
        ui->btn_draw->setText("结束绘制");
        ui->widget_analyse->setDrawMode(DrawForm::DRAW_POLYGON);
    }
    else
    {
        ui->btn_draw->setText("绘制区域");
        int cnt = ui->widget_analyse->polygons().count();
        if(cnt > 0)
        {
            QList<DrawForm::DrawPolygon> polygons = ui->widget_analyse->polygons();
            for(int i = 0; i < cnt; ++i)
            {
                polygons[i].selected = false;
            }
            ui->widget_analyse->setPolygons(polygons);
        }
        ui->widget_analyse->setDrawMode(DrawForm::DRAW_NULL);
    }
}


void CoalForm::on_btn_drawclear_clicked()
{
    show_alarmExtern = false;
    ui->widget_analyse->clearPolygons();
}


void CoalForm::on_btn_getparam_clicked()
{
    if(!ui->checkBox->isChecked())
    {
        QJsonObject body;
        Singleton::Instance()->onSendParam("GetCoalSpdParam", body);
        show_alarmExtern = true;
    }
    else
    {
        QJsonObject body;
        body.insert("chnId", myApp::current_chnnid);
        Singleton::Instance()->onSendParam("GetColidarPileCoalParam", body);
    }
}

void CoalForm::on_btn_setparam_clicked()
{
    if(!ui->checkBox->isChecked())
    {
        QJsonArray refZoneArr;
        if(ui->widget_analyse->polygons().count() > 0)
        {
            DrawForm::DrawPolygon polygon = ui->widget_analyse->polygons().at(0);

            for(int j = 0; j < polygon.polygon.count(); ++j)
            {
                QPointF pointF = ui->widget_analyse->point2PointF(polygon.polygon.at(j));
                QJsonObject zoneObj;
                zoneObj.insert("id", j + 1);
                zoneObj.insert("x", pointF.x());
                zoneObj.insert("y", pointF.y());
                refZoneArr.append(zoneObj);
            }
        }
        QJsonObject body;
        body.insert("threshAuto", ui->cbx_auto->currentIndex());
        body.insert("thresh", ui->led_thresh->text().toInt());
        body.insert("maxRefZone", refZoneArr );
        body.insert("func",  ui->cbx_func->currentIndex());
        body.insert("factor", ui->led_factor->text().toFloat());
        body.insert("density", ui->led_density->text().toFloat());
        body.insert("xDisplacement", ui->led_xDisplacement->text().toInt());
        body.insert("yDisplacement", ui->led_yDisplacement->text().toInt());
        body.insert("displacement", ui->led_displacement->text().toInt());
        body.insert("maxFiltering", ui->led_maxFiltering->text().toInt());
        body.insert("minFiltering", ui->led_minFiltering->text().toInt());
        body.insert("maxAngle", ui->led_maxAngle->text().toInt());
        body.insert("minAngle", ui->led_minAngle->text().toInt());

        Singleton::Instance()->onSendParam("SetCoalSpdParam", body);

    }

    else
    {
        QJsonObject body;
        QJsonArray ZoneArr;
        int cnt = ui->widget_analyse->polygons().count();
        if(cnt > 0)
        {
            DrawForm::DrawPolygon polygon = ui->widget_analyse->polygons().at(0);

            for(int j = 0; j < polygon.polygon.count(); ++j)
            {
                QPointF pointF = ui->widget_analyse->point2PointF(polygon.polygon.at(j));
                QJsonObject zoneObj;
                //zoneObj.insert("id", j + 1);
                zoneObj.insert("x", pointF.x());
                zoneObj.insert("y", pointF.y());
                ZoneArr.append(zoneObj);
            }
        }
        body.insert("maxZones", ZoneArr);
        body.insert("chnId", myApp::current_chnnid);
        Singleton::Instance()->onSendParam("SetColidarPileCoalParam", body);
    }
}

void CoalForm::on_btn_baseline_clicked()
{
    QJsonObject body;
    Singleton::Instance()->onSendParam("SetCoalSpdBaseline", body);
}

void CoalForm::onRealtimeImage(WsBinHeader header, QByteArray image)
{
    ImageHeader imageHeader;
    int imageHeaderLen = sizeof(ImageHeader);
    memcpy(&imageHeader, header.reserved, imageHeaderLen);

    if(imageHeader.type == WSIMAGE_TYPE::WSIMAGE_TYPE_DETECTOR)
    {
        ui->widget_analyse->setImage(image);
    }
    else if(imageHeader.type == WSIMAGE_TYPE::WSIMAGE_TYPE_COAL)
    {
        ui->widget_coalSection->setImage(image);
    }
}
void CoalForm::onAlarmImage(WsBinHeader header, QByteArray image, AlarmExtern alarmExtern)
{
    ImageHeader imageHeader;
    int imageHeaderLen = sizeof(ImageHeader);
    memcpy(&imageHeader, header.reserved, imageHeaderLen);
    if(imageHeader.type == WSIMAGE_TYPE::WSIMAGE_TYPE_ORIGIN)
    {
        ui->widget_analyse->setImage(image);
#if 0
        if(!alarmExtern.boxes.isEmpty())
        {
            QJsonParseError jsonParseError;
            QJsonDocument jsonDoc = QJsonDocument::fromJson(alarmExtern.boxes.toLatin1().data(), &jsonParseError);
            if(!jsonDoc.isEmpty() && (jsonParseError.error == QJsonParseError::NoError))
            {
                if(jsonDoc.isArray())
                {
                    QList<DrawForm::DrawPolygon> polygons;
                    QJsonArray zonesArr = jsonDoc.array();

                    for(auto i = 0; i < zonesArr.count(); ++i)
                    {
                        if(zonesArr.at(i).isArray())
                        {
                            QJsonArray zoneArr = zonesArr.at(i).toArray();
                            DrawForm::DrawPolygon polygon;

                            for(auto j = 0; j < zoneArr.count(); ++j)
                            {
                                QJsonObject zoneObj = zoneArr.at(j).toObject();
                                QPointF pointF(zoneObj.value("x").toDouble(), zoneObj.value("y").toDouble());
                                QPoint point = ui->widget_analyse->pointF2Point(pointF);
                                polygon.polygon.append(point);
                            }

                            polygons.append(polygon);
                        }
                    }

                    ui->widget_analyse->setPolygons(polygons);
                }
            }
        }
#endif
    }
    else if(imageHeader.type == WSIMAGE_TYPE::WSIMAGE_TYPE_COAL)
    {
        if(ui->btn_coalimage->text() == "打开预览")
        {
            return;
        }
        ui->widget_coalSection->setImage(image);
#if 0
        if(!alarmExtern.boxes.isEmpty())
        {
            QJsonParseError jsonParseError;
            QJsonDocument jsonDoc = QJsonDocument::fromJson(alarmExtern.boxes.toLatin1().data(), &jsonParseError);
            if(!jsonDoc.isEmpty() && (jsonParseError.error == QJsonParseError::NoError))
            {
                if(jsonDoc.isArray())
                {
                    QList<DrawForm::DrawPolygon> polygons;
                    QJsonArray zonesArr = jsonDoc.array();

                    for(auto i = 0; i < zonesArr.count(); ++i)
                    {
                        if(zonesArr.at(i).isArray())
                        {
                            QJsonArray zoneArr = zonesArr.at(i).toArray();
                            DrawForm::DrawPolygon polygon;

                            for(auto j = 0; j < zoneArr.count(); ++j)
                            {
                                QJsonObject zoneObj = zoneArr.at(j).toObject();
                                QPointF pointF(zoneObj.value("x").toDouble(), zoneObj.value("y").toDouble());
                                QPoint point = ui->widget_coalSection->pointF2Point(pointF);
                                polygon.polygon.append(point);
                            }
                            polygons.append(polygon);
                        }
                    }

                    ui->widget_coalSection->setPolygons(polygons);

                }
            }
        }
#endif
    }

}
void CoalForm::onCoalSpdValue(QJsonObject obj)
{
    m_chnid = obj.value("chnId").toString();
    QString coalInfo = tr("coalVolume") + QString(":%1%, ").arg(obj.value("coalVolume").toDouble()) +
                       tr("beltVolume") + QString(":%1 t/h, ").arg(QString::number(obj.value("beltVolume").toDouble() * 360, 'f', 3)) +
                       tr("beltSpd") + QString(":%1 m/s,").arg(obj.value("beltSpd").toDouble()) +
                       QString("beltAlert:%1").arg(obj.value("beltAlert").toBool());
    ui->label_coalInfo->setText(coalInfo);

//    if(m_firIn)
//    {
//        m_firIn = false;

//        QDateTime beginTime = QDateTime::currentDateTime();
//        QDateTime endTime = beginTime.addMSecs(30 * 1000);
//        m_dateAxisX->setMin(beginTime);
//        m_dateAxisX->setMax(endTime);
//    }

//    if(m_series->count() > 59)
//    {
//        m_series->remove(0);
//        QDateTime endTime = QDateTime::currentDateTime();
//        QDateTime beginTime = endTime.addMSecs(-30 * 1000);
//        m_dateAxisX->setMin(beginTime);
//        m_dateAxisX->setMax(endTime);
//    }
    m_dateAxisX->setMin(QDateTime::currentDateTime().addSecs(-60 * 1));       //系统当前时间的前一秒
    m_dateAxisX->setMax(QDateTime::currentDateTime().addSecs(0));
    qint64 x = QDateTime::currentMSecsSinceEpoch();

    m_series->append(x, obj.value("coalVolume").toDouble());
    m_series->show();
}

void CoalForm::onCoalSpdParam(QJsonObject obj)
{
    ui->cbx_auto->setCurrentIndex(obj.value("threshAuto").toInt());
    ui->led_thresh->setText(QString::number(obj.value("thresh").toInt()));

    QList<DrawForm::DrawPolygon> polygons;
    DrawForm::DrawPolygon polygon;
    QJsonArray zoneArr =  obj.value("maxRefZone").toArray();
    for(auto j = 0; j < zoneArr.count(); ++j)
    {
        QJsonObject zoneObj = zoneArr.at(j).toObject();
        QPointF pointF(zoneObj.value("x").toDouble(), zoneObj.value("y").toDouble());
        QPoint point = ui->widget_analyse->pointF2Point(pointF);
        polygon.polygon.append(point);
    }
    polygons.append(polygon);
    ui->widget_analyse->set_detect_Polygons(polygons);

    ui->cbx_func->setCurrentIndex(obj.value("func").toInt());
    ui->led_factor->setText(QString::number(obj.value("factor").toDouble(), 'f', 6));
    ui->led_density->setText(QString::number(obj.value("density").toDouble(), 'f', 6));
    ui->led_xDisplacement->setText(QString::number(obj.value("xDisplacement").toInt()));
    ui->led_yDisplacement->setText(QString::number(obj.value("yDisplacement").toInt()));
    ui->led_displacement->setText(QString::number(obj.value("displacement").toInt()));
    ui->led_maxFiltering->setText(QString::number(obj.value("maxFiltering").toInt()));
    ui->led_minFiltering->setText(QString::number(obj.value("minFiltering").toInt()));
    ui->led_maxAngle->setText(QString::number(obj.value("maxAngle").toInt()));
    ui->led_minAngle->setText(QString::number(obj.value("minAngle").toInt()));
    QMessageBox::information(nullptr, "提示", "煤量调速参数获取成功");

}

void CoalForm::onGetColidarPileCoalParam(QJsonObject obj)
{
    if(obj.value("maxZones").isArray())
    {
        QJsonArray zoneArr = obj.value("maxZones").toArray();
        QList<DrawForm::DrawPolygon> polygons;
        DrawForm::DrawPolygon polygon;
        for (int j = 0; j < zoneArr.count(); ++j)
        {
            if(zoneArr.at(j).isObject())
            {
                QJsonObject zoneObj = zoneArr.at(j).toObject();
                QPointF pointf(zoneObj.value("x").toDouble(), zoneObj.value("y").toDouble());
                QPoint point = ui->widget_analyse->pointF2Point(pointf);
                polygon.polygon.push_back(point);
            }
        }
        polygons.push_back(polygon);
        ui->widget_analyse->set_detect_Polygons(polygons);
    }
    QMessageBox::information(nullptr, "提示", "激光雷达参数获取成功");
}

void CoalForm::on_btn_RealTimeImage_clicked(bool checked)
{
    if(checked)
    {
        ui->btn_RealTimeImage->setText("关闭预览");
        m_timer->start();
    }
    else
    {
        ui->btn_RealTimeImage->setText("打开预览");
        m_timer->stop();
        ui->widget_analyse->clear();
    }

}

void CoalForm::on_btn_coalimage_clicked()
{
    QJsonObject body;
    body.insert("chnId", m_chnid);
    body.insert("enable", ui->btn_coalimage->text() == "打开预览" ? 1 : 0);
    Singleton::Instance()->onSendParam("SetAlarmInfo", body);
}

void CoalForm::on_btn_debug_clicked()
{
    if(ui->btn_debug->text() == "开始调试")
    {
        m_timer_2->start();
        ui->btn_debug->setText("关闭调试");
    }
    else
    {
        m_timer_2->stop();
        ui->btn_debug->setText("开始调试");
    }
}

void CoalForm::on_checkBox_stateChanged(int arg1)
{
    if(arg1 == 0)
    {
        ui->cbx_auto->setHidden(false);
        ui->cbx_func->setHidden(false);
        ui->led_thresh->setHidden(false);
        ui->led_factor->setHidden(false);
        ui->led_density->setHidden(false);
        ui->led_xDisplacement->setHidden(false);
        ui->led_yDisplacement->setHidden(false);
        ui->led_displacement->setHidden(false);
        ui->led_maxFiltering->setHidden(false);
        ui->led_minFiltering->setHidden(false);
        ui->led_maxAngle->setHidden(false);
        ui->led_minAngle->setHidden(false);
        QList<QLabel*> lab_list = ui->groupBox->findChildren<QLabel*>();
        for ( QList<QLabel*>::iterator iter = lab_list.begin(); iter != lab_list.end(); ++iter)
        {
            QWidget* item = *iter;
            item->setHidden(false);
        }

    }
    else if(arg1 == 2)
    {
        ui->cbx_auto->setHidden(true);
        ui->cbx_func->setHidden(true);
        ui->led_thresh->setHidden(true);
        ui->led_factor->setHidden(true);
        ui->led_density->setHidden(true);
        ui->led_xDisplacement->setHidden(true);
        ui->led_yDisplacement->setHidden(true);
        ui->led_displacement->setHidden(true);
        ui->led_maxFiltering->setHidden(true);
        ui->led_minFiltering->setHidden(true);
        ui->led_maxAngle->setHidden(true);
        ui->led_minAngle->setHidden(true);
        QList<QLabel*> lab_list = ui->groupBox->findChildren<QLabel*>();
        for ( QList<QLabel*>::iterator iter = lab_list.begin(); iter != lab_list.end(); ++iter)
        {
            QWidget* item = *iter;
            item->setHidden(true);
        }
    }
}


